package com.shengwei.truck.driver.socket.dataconvert;


/**
 *字节转换，如常用的16进制字符串转byte[],或者byte[]打印成16进制字符串
 */
public class ByteUtils {

    /**
     * 16进制样式的字符串转为真正的byte数组，2个字符组合为一个byte
     * @param hexString
     * @return
     */
    public static byte[] hexString2Bytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.trim().replaceAll("\\s*", "");
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    /**
     * 字节数转为16进制串，1个byte元素转为2个字符，如0x01---"01"
     * @param b
     * @return
     */
    public static String byteToHexString(byte b) {
        String stmp = Integer.toHexString(b & 0xFF);
        stmp = (stmp.length() == 1) ? "0" + stmp : stmp;
        return stmp.toUpperCase();
    }


    /**
     * 1字节转int
     * @param b
     * @return
     */
    public static int byteToInt(byte b) {
        return Integer.valueOf(b);
    }

    /**
     * 字节数组转为16进制串，1个byte元素转为2个字符，如0x01--->"01"， 再如0x01,0x02--->"0102"
     * @param b
     * @return
     */
    public static String byteToHexString(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (byte c : b) {
            stmp = Integer.toHexString(c & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");// ÿλ�����ÿո�ָ�
        }
        return sb.toString().toUpperCase().trim();
    }


    /**
     * 二进制形式的字符串转为 16进制字符串，如"00000001"转为 "01"
     * @param binaryStr
     * @return
     */
    public static String binaryStr2HexStr(String binaryStr) {

        String[] strs = binaryStr.split("\\s+");
        String hexStr = "";
        for (String string : strs) {
            String hex = Integer.toString(Integer.parseInt(string, 2), 16);
            hexStr += hex;
        }
        return hexStr;
    }


    /**
     * 浮点数转为byte数组
     * @param a
     * @return
     */
    public static byte[] floatToBytes(float a) {
        byte[] data = new byte[4];
        if (a == 0) {
            for (int i = 0; i < 4; i++) {
                data[i] = 0x00;
            }
            return data;
        }
        Integer[] intdata = {0, 0, 0, 0};
        a = Math.abs(a);
        float floatpart = a % 1;
        int intpart = (int) (a / 1);
        String intString = "";
        String floatString = "";
        String result = "";
        String subResult = "";
        int zhishu = 0;
        if (intpart == 0) {
            intString += "0";
        }
        while (intpart != 0) {
            intString = intpart % 2 + intString;
            intpart = intpart / 2;
        }
        while (floatpart != 0) {
            floatpart *= 2;
            if (floatpart >= 1) {
                floatString += "1";
                floatpart -= 1;
            } else {
                floatString += "0";
            }
        }
        result = intString + floatString;
        intpart = (int) (a / 1);
        if (intpart > 0) {
            zhishu = intString.length() - 1;
        } else {
            for (int i = 0; i < floatString.length(); i++) {
                zhishu--;
                if (floatString.charAt(i) == '1') {
                    break;
                }
            }

        }
        if (zhishu >= 0) {
            subResult = result.substring(intString.length() - zhishu);
        } else {
            subResult = floatString.substring(-zhishu);
        }
        zhishu += 127;
        if (subResult.length() <= 7) {

            for (int i = 0; i < 7; i++) {
                if (i < subResult.length()) {
                    intdata[1] = intdata[1] * 2 + subResult.charAt(i) - '0';
                } else {
                    intdata[1] *= 2;
                }

            }
            if (zhishu % 2 == 1) {
                intdata[1] += 128;
            }
            data[1] = intdata[1].byteValue();
        } else if (subResult.length() <= 15) {
            int i = 0;
            for (i = 0; i < 7; i++) {
                intdata[1] = intdata[1] * 2 + subResult.charAt(i) - '0';
            }
            if (zhishu % 2 == 1) {
                intdata[1] += 128;
            }
            data[1] = intdata[1].byteValue();

            for (i = 7; i < 15; i++) {// ����8-15λ
                if (i < subResult.length()) {
                    intdata[2] = intdata[2] * 2 + subResult.charAt(i) - '0';
                } else {
                    intdata[2] *= 2;
                }
            }
            data[2] = intdata[2].byteValue();
        } else {
            int i = 0;
            for (i = 0; i < 7; i++) {
                intdata[1] = intdata[1] * 2 + subResult.charAt(i) - '0';
            }
            if (zhishu % 2 == 1) {
                intdata[1] += 128;
            }
            data[1] = intdata[1].byteValue();

            for (i = 7; i < 15; i++) {
                intdata[2] = intdata[2] * 2 + subResult.charAt(i) - '0';
            }
            data[2] = intdata[2].byteValue();

            for (i = 15; i < 23; i++) {
                if (i < subResult.length()) {
                    intdata[3] = intdata[3] * 2 + subResult.charAt(i) - '0';
                } else {
                    intdata[3] *= 2;
                }

            }
            data[3] = intdata[3].byteValue();
        }

        intdata[0] = zhishu / 2;
        if (a < 0) {
            intdata[0] += 128;
        }
        data[0] = intdata[0].byteValue();
        byte[] data2 = new byte[4];
        for (int i = 0; i < 4; i++) {
            data2[i] = data[3 - i];
        }
        return data2;
    }

    /**
     * 0-15转为16进制字符串 0-9，ABCDEF
     * @param n
     * @return
     */
    private static String toHexUtil(int n) {
        String rt = "";
        switch (n) {
            case 10:
                rt += "A";
                break;
            case 11:
                rt += "B";
                break;
            case 12:
                rt += "C";
                break;
            case 13:
                rt += "D";
                break;
            case 14:
                rt += "E";
                break;
            case 15:
                rt += "F";
                break;
            default:
                rt += n;
        }
        return rt;
    }

    /**
     * 整数转为16进制字符串
     * @param n
     * @return
     */
    public static String toHex(int n) {
        StringBuilder sb = new StringBuilder();
        if (n / 16 == 0) {
            return toHexUtil(n);
        } else {
            String t = toHex(n / 16);
            int nn = n % 16;
            sb.append(t).append(toHexUtil(nn));
        }
        return sb.toString();
    }

    /**
     *  字符串 对应的 16进制形式的ASCII码串
     * @param str
     * @return
     */
    public static String strToHexStrAscii(String str) {
        StringBuilder sb = new StringBuilder();
        byte[] bs = str.getBytes();
        for (int i = 0; i < bs.length; i++)
            sb.append(toHex(bs[i]));
        return sb.toString();
    }


    /**
     * 16进制形式的ASCII码串 翻译成 字符串
     * @param hexStr
     * @return
     */
    public static String hexStrAsciiToStr(String hexStr) {
        byte[] bytes = hexString2Bytes(hexStr);
        return new String(bytes);
    }
}